<template>
  <div id="LogInfo">
    <div class="areaAll">
      <vxe-toolbar perfect>
        <template #buttons>
          <span class="smallTitle">操作日期</span>
          <vxe-input v-model="form.beginLog" placeholder="开始日期" type="datetime"></vxe-input>
          <span >-</span>
          <vxe-input
            v-model="form.endLog"
            placeholder="截至日期"
            type="datetime"
            class="vxeInputSearch"
          ></vxe-input>
          <span class="smallTitle">服务名称</span>
          <vxe-input
            v-model="form.serviceName"
            placeholder="服务名称"
            type="text"
            class="vxeInputSearch"
          ></vxe-input>
          <span class="smallTitle">客户机IP</span>
          <vxe-input
            v-model="form.machineIp"
            placeholder="客户机IP"
            type="text"
            class="vxeInputSearch"
          ></vxe-input>
          <span class="smallTitle">业务名称</span>
          <vxe-input
            v-model="form.businessName"
            placeholder="业务名称"
            type="text"
            clearable
            class="vxeInputSearch"
          ></vxe-input>
          <!-- <el-button icon="Search" @click="findLogPageList" class="button-blue searchBtn"
            >查询</el-button
          > -->
          <vxe-button
            type="text"
            class="button-blue searchBtn"
            icon="vxe-icon-search"
            content="查询"
            :loading="loading"
            @click="findLogPageList"
          ></vxe-button>
        </template>
      </vxe-toolbar>

      <div class="tableBody">
        <vxe-table
          ref="logTable"
          border
          height="auto"
          class="mytable-scrollbar"
          :data="logList"
          :loading="loading"
          :expand-config="{ expandAll: true, reserve: true }"
          :row-config="{ isCurrent: true, isHover: true }"
          :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }"
          :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
          resizable
          show-overflow
          keep-source
          @current-change="roleRowClick"
        >
          <vxe-column field="id" title="交易流水号"></vxe-column>
          <!-- <vxe-column field="hospitalCode" title="医院编码"> </vxe-column> -->
          <!-- <vxe-column field="hospitalName" title="医院名称"></vxe-column> -->
          <vxe-column field="machineName" title="客户机名称"> </vxe-column>
          <!-- <vxe-column field="machineIp" title="IP"> </vxe-column> -->
          <vxe-column field="userName" title="操作员" width="100"> </vxe-column>
          <vxe-column field="module" title="功能模块"> </vxe-column>
          <vxe-column field="businessName" title="业务名称"> </vxe-column>
          <vxe-column field="content" title="操作内容" width="500"> </vxe-column>
          <!-- <vxe-column field="operationType" title="服务类别"> </vxe-column> -->
          <!-- <vxe-column field="requestMethod" title="请求方式"> </vxe-column> -->

          <!-- <vxe-column field="requestUrl" title="服务路径"> </vxe-column> -->
          <vxe-column field="operateTime" title="操作时间" :formatter="formatOperateTime">
          </vxe-column>
          <vxe-column field="createTime" title="结束时间" :formatter="formatOperateTime">
          </vxe-column>
          <vxe-column field="takeTime" title="耗时/毫秒" width="60"> </vxe-column>
        </vxe-table>

        <vxe-pager
          align="left"
          max-height="32px"
          :current-page.sync="page.currentPage"
          :page-size.sync="page.pageSize"
          :total="page.totalResult"
          :layouts="[
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'Sizes',
            'FullJump',
            'Total'
          ]"
          @page-change="handleSizeChange($event)"
        ></vxe-pager>
      </div>

      <el-drawer v-model="showPloyeeDialog">
        <template #header>
          <h4>{{ title }}</h4>
        </template>
        <template #default>
          <div>
            <el-input type="textarea" :value="reqJson" :rows="35"></el-input>
          </div>
        </template>
        <template #footer>
          <div style="flex: auto"></div>
        </template>
      </el-drawer>

      <el-dialog
        title="操作日志详情"
        width="900px"
        append-to-body
        v-model="showLogDetails"
        style="margin-top: 10vh"
      >
        <el-descriptions :column="2" border v-loading="dialogLoading">
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <user />
                </el-icon>
                操作员
              </div>
            </template>
            {{ formDetails.userName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <iphone />
                </el-icon>
                操作模块
              </div>
            </template>
            {{ formDetails.module }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Star />
                </el-icon>
                日志级别
              </div>
            </template>
            {{ formDetails.logLevel }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Monitor />
                </el-icon>
                计算机
              </div>
            </template>
            <el-tag size="small">{{ formDetails.machineName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <office-building />
                </el-icon>
                IP地址
              </div>
            </template>
            {{ formDetails.machineIp }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <tickets />
                </el-icon>
                请求方式
              </div>
            </template>
            <el-tag size="small">{{ formDetails.requestMethod }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Location />
                </el-icon>
                请求地址
              </div>
            </template>
            {{ formDetails.requestUrl }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <AlarmClock />
                </el-icon>
                操作时间
              </div>
            </template>
            {{ formDetails.operateTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Timer />
                </el-icon>
                消耗时间
              </div>
            </template>
            <el-tag size="small">{{ formDetails.takeTime }}/毫秒</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Refresh />
                </el-icon>
                操作状态
              </div>
            </template>
            <el-tag size="small">
              <div v-if="formDetails.flag === '0'">正常</div>
              <div v-else-if="formDetails.flag === '1'">失败</div>
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <ChatSquare />
                </el-icon>
                操作內容
              </div>
            </template>
            {{ formDetails.content }}
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :column="1" border v-if="activeNames" v-loading="dialogLoading">
          <!-- 这里是您的描述内容 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <ChromeFilled />
                </el-icon>
                操作方法
              </div>
            </template>
            <el-scrollbar>
              <div class="selectable">{{ formDetails.method }}</div>
            </el-scrollbar>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Tickets />
                </el-icon>
                请求参数
              </div>
            </template>
            <el-scrollbar>
              <div class="selectable">{{ formDetails.reqParam }}</div>
            </el-scrollbar>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Tickets />
                </el-icon>
                返回参数
              </div>
            </template>
            <el-scrollbar>
              <div class="selectable">{{ formDetails.repParam }}</div>
            </el-scrollbar>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, computed, defineProps } from 'vue';
import { pageSizes, formatDateTime } from '../utils/common';
import { AppStore } from '../stores/store';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
let { proxy }: any = getCurrentInstance();

// 全局变量定义区 ==========
const props = defineProps({
  requestUrl: { type: String, default: '' }
});

let store = AppStore();
const size = ref('');
let title = ref('');

// el-drawer
let reqJson = ref('');
const showPloyeeDialog = ref(false); //展开抽屉状态

let logTable = ref(); //日志表格ref
let logList: any = reactive([]); //日志表格数据
let loading = ref(false); //表格加载
let dialogLoading = ref(false); //点击当前行的弹框数据加载

const showLogDetails = ref(false); //弹框展开状态
const activeNames = ref(false); //当身份是管理员时可以看到弹框的最下面3个数据 操作方法 请求和返回参数

let form = reactive({
  beginLog: formatDateTime(getThisMonthFirstDay(), 'yyyy-MM-dd'),
  endLog: formatDateTime(getThisMonthNewDay(), 'yyyy-MM-dd 23:59:59'),
  serviceName: '',
  machineIp: '',
  username: '',
  businessName: ''
});

let formDetails = reactive({
  module: '',
  userName: '',
  reqParam: '',
  repParam: '',
  flag: '',
  takeTime: '',
  serviceName: '',
  hospitalName: '',
  hospitalCode: '',
  machineIp: '',
  content: '',
  method: '',
  requestMethod: '',
  requestUrl: '',
  machineName: '',
  operateTime: '',
  logLevel: ''
});

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px'
  };
  return {
    marginRight: marginMap[size.value] || marginMap.default
  };
});

// 方法定义区 =============
//这个月第一天日期
function getThisMonthFirstDay() {
  let today = new Date();
  today.setDate(1);
  today.setHours(0, 0, 0, 0);
  return today;
}
//当前日期
function getThisMonthNewDay() {
  let today = new Date();
  return today;
}
// 格式化日期时间
function formatOperateTime({ cellValue, row, column }) {
  // 假设cellValue是一个时间戳，你可以使用Date对象将其格式化为包含毫秒的形式
  const date = new Date(cellValue);
  return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss'); // 这会返回包含毫秒的 ISO 8601 格式的时间字符串
}

//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findLogPageList();
}

onMounted(() => {
  findLogPageList(); //查找用户列表
});

// 页面获取日志表格数据
function findLogPageList() {
  loading.value = true;
  logList.length = 0;
  const data = {
    beginLog: form.beginLog,
    endLog: form.endLog,
    serviceName: form.serviceName,
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    requestUrl: props.requestUrl,
    businessName: form.businessName
  };
  const url = 'api/log/getPageLogging';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      logList.push(...res.data.logPageList.records);
      page.totalResult = res.data.logPageList.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      // VxeMessage('搜索日志列表失败', VxeNotifyType.error);
    });
}

// 清空弹框
function clearDialog() {
  // 全部清空
  formDetails.content = '';
  formDetails.userName = '';
  formDetails.reqParam = '';
  formDetails.repParam = '';
  formDetails.flag = '';
  formDetails.serviceName = '';
  formDetails.hospitalName = '';
  formDetails.hospitalCode = '';
  formDetails.machineIp = '';
  formDetails.method = '';
  formDetails.requestMethod = '';
  formDetails.requestUrl = '';
  formDetails.takeTime = '';
  formDetails.module = '';
  formDetails.machineName = '';
  formDetails.operateTime = '';
  formDetails.logLevel = '';
}
// 获取当前条的详情信息
const roleRowClick = ({ row }: any) => {
  let userInfo = store.userInfo;
  if (userInfo.realname === '管理员') {
    activeNames.value = true;
  }
  showLogDetails.value = true;
  clearDialog(); //清空前面弹框数据
  dialogLoading.value = true;
  const url = 'api/log/getLoggingById/' + row.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      formDetails.content = res.data.content;
      formDetails.userName = res.data.userName;
      formDetails.reqParam = res.data.reqParam;
      formDetails.repParam = res.data.repParam;
      formDetails.flag = res.data.flag;
      formDetails.serviceName = res.data.serviceName;
      formDetails.hospitalName = res.data.hospitalName;
      formDetails.hospitalCode = res.data.hospitalCode;
      formDetails.machineIp = res.data.machineIp;
      formDetails.method = res.data.method;
      formDetails.requestMethod = res.data.requestMethod;
      formDetails.requestUrl = res.data.requestUrl;
      formDetails.takeTime = res.data.takeTime;
      formDetails.module = res.data.module;
      formDetails.machineName = res.data.machineName;
      formDetails.operateTime = formatDateTime(res.data.operateTime, 'yyyy-MM-dd hh:mm:ss');
      formDetails.logLevel = res.data.logLevel;
      dialogLoading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      dialogLoading.value = false;
      // VxeMessage('搜索当前条的详情信息失败', VxeNotifyType.error);
    });
};
</script>
<style lang="scss" scoped>
.selectable {
  -webkit-user-select: text; /* Safari 和 Chrome */
  -moz-user-select: text; /* Firefox */
  -ms-user-select: text; /* Internet Explorer/Edge */
  user-select: text; /* 标准语法 */
  max-width: 700px;
  width: auto;
  max-height: 100px;
  height: auto;
  overflow-wrap: break-word;
}

#LogInfo {
  height: 100%;
  .areaAll {
    height: 100%;
    .smallTitle {
      margin-right:5px;
    }
    .searchBtn {
      margin-left: 5px;
    }
    .tableBody {
      height: calc(100% - 30px - 32px);
      // 每个单元格左内边距
      :deep(.vxe-cell) {
        padding-left: 5px;
      }
    }
    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
      .el-descriptions {
        width: 100%;
      }
    }
  }
}
// 操作日志详情弹框的label标签统一宽度
:deep(.el-descriptions__label) {
  width: 150px;
}
</style>
